﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sl.Duplex {
	public static class Duplex_expand {
		/// <summary>
		/// 这个程序要求一个支持读和读超时的流，并且会将读超时设置为0。会对读到的每个Byte执行recvByteTo
		/// </summary>
		/// <param name="s"></param>
		/// <param name="recvByteTo"></param>
		public static void readAllBytes(this IDuplex ds, Action<byte> onRecvByte) {
			byte[] ba = new byte[64];
			//ds.ReadTimeout = 0;
			while (true) {
				int recvnum;
				try {
					recvnum = ds.Read(ba, 0, 64);
					if (recvnum <= 0) {
						ds.closePort();
						return;
					}
				} catch (System.TimeoutException) {
					return;
				}
				for (int i = 0; i < recvnum; i++) {
					onRecvByte(ba[i]);
				}
			}
		}
		public static void sendAllBytes(this IDuplex ds, byte[] b, int offset = 0, int counter = -1) {
			if(counter == -1) {
				counter = b.Length;
			}
			ds.Write(b,offset,counter);
		}
	}

}
